﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class View_login : System.Web.UI.UserControl
{
    UserBus usBus;
    protected void Page_Load(object sender, EventArgs e)
    {
        usBus = new UserBus();
        if (!IsPostBack) 
        {
            checkCookie();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string username = txtUserName.Text;
        string pass = txtPassword.Text;
        string passMD5 = usBus.MaHoaMD5(pass);
        if (usBus.checkLogin(username,passMD5))
        {
            Session["username"] = txtUserName.Text;
            User urs = usBus.getUserByUserName(Session["username"].ToString());
            Session["fullname"] = urs.FullName;
            if (chkRemember.Checked == true)
            {

                HttpCookie cookieRememberMe = new HttpCookie("RememberMe");
                cookieRememberMe = new HttpCookie("RememberMe");
                cookieRememberMe.Values.Add("UserName", txtUserName.Text.Trim());
                cookieRememberMe.Values.Add("Password", passMD5);
                cookieRememberMe.Values.Add("CheckBox", "True");
                cookieRememberMe.Expires = DateTime.Now.AddDays(30);
                Response.Cookies.Add(cookieRememberMe);

            }
            else
            {

            }
            Response.Redirect("~/default.aspx");
        }
        else 
        {
            ScriptManager.RegisterStartupScript(this, typeof(Page), "Tin Tuc Online", "<script>alert('tài khoản hoặc mật khẩu không đúng')</script>", false);
            return;
        }
    }
    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Session["username"] = "";
        Response.Redirect("~/default.aspx");
    }
    public void checkCookie()
    {
        if (Request.Cookies["RememberMe"] != null)
        {
            HttpCookie cookieRememberMe = Request.Cookies.Get("RememberMe");
            txtUserName.Text = cookieRememberMe.Values["UserName"].ToString();
            txtPassword.Attributes.Add("Value", cookieRememberMe.Values["Password"].ToString());

            if (usBus.checkLogin(txtUserName.Text.Trim(), txtPassword.Text.Trim()))
            {
                User us = new User();
                us = usBus.getUserByUserName(txtUserName.Text.Trim());
                Session["username"] = txtUserName.Text.Trim();
                Session["fullname"] = us.FullName;
            }
        }
    }
}